// pages/devices/devices.js
const app = getApp()
const { deviceAPI } = require('../../utils/api.js')

Page({
  data: {
    loading: false,
    fromPage: '',
    currentDevice: null,
    operationHistory: [],
    deviceId: ''
  },

  onLoad(options) {
    const { deviceId, from } = options
    this.setData({
      deviceId: deviceId,
      fromPage: from || ''
    })
    
    this.loadDeviceDetail(deviceId)
  },

  onShow() {
    // 页面显示时刷新设备状态
    if (this.data.deviceId) {
      this.loadDeviceDetail(this.data.deviceId)
    }
  },

  onPullDownRefresh() {
    if (this.data.deviceId) {
      this.loadDeviceDetail(this.data.deviceId)
    }
    wx.stopPullDownRefresh()
  },

  // 加载设备详情
  async loadDeviceDetail(deviceId) {
    this.setData({ loading: true })
    
    try {
      // 从全局数据获取设备信息
      let device = app.globalData.deviceList.find(d => d.id === deviceId)
      
      if (!device) {
        // 如果全局数据中没有，从API获取
        const devices = await deviceAPI.getDeviceList()
        device = devices.find(d => d.id === deviceId)
      }
      
      if (device) {
        // 获取设备详细信息
        const deviceDetail = await this.getDeviceDetail(device)
        const operationHistory = await this.getOperationHistory(deviceId)
        
        this.setData({
          currentDevice: deviceDetail,
          operationHistory
        })
      } else {
        wx.showToast({
          title: '设备不存在',
          icon: 'error'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    } catch (error) {
      console.error('加载设备详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 获取设备详细信息
  async getDeviceDetail(device) {
    try {
      // 获取设备实时状态
      const status = await deviceAPI.getDeviceStatus(device.id)
      
      return {
        ...device,
        ...status,
        // 模拟一些额外数据
        usageToday: Math.floor(Math.random() * 10),
        energyUsage: (Math.random() * 5).toFixed(1),
        lastUsed: this.formatLastUsedTime(),
        firmware: 'v1.' + Math.floor(Math.random() * 5) + '.0',
        addTime: '2024-01-01'
      }
    } catch (error) {
      console.error('获取设备状态失败:', error)
      return device
    }
  },

  // 获取操作记录
  async getOperationHistory(deviceId) {
    // 模拟操作记录数据
    return [
      {
        time: '今天 14:30',
        description: '设备开启',
        icon: '/images/icons/power-on.png',
        type: 'power_on'
      },
      {
        time: '今天 12:15',
        description: '亮度调整为80%',
        icon: '/images/icons/brightness.png',
        type: 'brightness'
      },
      {
        time: '今天 10:00',
        description: '设备关闭',
        icon: '/images/icons/power-off.png',
        type: 'power_off'
      },
      {
        time: '昨天 20:45',
        description: '色温调整为暖色',
        icon: '/images/icons/color.png',
        type: 'color'
      }
    ]
  },

  // 格式化最后使用时间
  formatLastUsedTime() {
    const now = new Date()
    const hours = now.getHours()
    const minutes = now.getMinutes()
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
  },

  // 获取设备类型文本
  getDeviceTypeText(type) {
    const typeMap = {
      'light': '智能灯',
      'ac': '空调',
      'tv': '电视',
      'camera': '摄像头',
      'sensor': '传感器',
      'socket': '智能插座'
    }
    return typeMap[type] || '智能设备'
  },

  // 返回上一页
  onBack() {
    if (this.data.fromPage) {
      wx.navigateBack()
    } else {
      wx.switchTab({
        url: '/pages/index/index'
      })
    }
  },

  // 更多操作
  onMoreActions() {
    wx.showActionSheet({
      itemList: ['设备重命名', '设备迁移', '固件升级', '删除设备'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            this.onRenameDevice()
            break
          case 1:
            this.onMoveDevice()
            break
          case 2:
            this.onFirmwareUpdate()
            break
          case 3:
            this.onDeleteDevice()
            break
        }
      }
    })
  },

  // 电源开关切换
  async onPowerToggle(e) {
    const isOn = e.detail.value
    const device = this.data.currentDevice
    
    if (device.status === 'offline') {
      wx.showToast({
        title: '设备离线，无法操作',
        icon: 'error'
      })
      return
    }
    
    try {
      await deviceAPI.controlDevice(device.id, {
        powerState: isOn ? 'on' : 'off'
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { powerState: isOn ? 'on' : 'off' })
      
      // 更新本地数据
      const updatedDevice = { ...device, powerState: isOn ? 'on' : 'off' }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      this.addOperationRecord(
        isOn ? 'power_on' : 'power_off',
        `设备${isOn ? '开启' : '关闭'}`
      )
      
      wx.showToast({
        title: isOn ? '设备已开启' : '设备已关闭',
        icon: 'success'
      })
      
    } catch (error) {
      console.error('控制设备失败:', error)
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    }
  },

  // 亮度调节
  async onBrightnessChange(e) {
    const brightness = e.detail.value
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        brightness: parseInt(brightness)
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { brightness: parseInt(brightness) })
      
      // 更新本地数据
      const updatedDevice = { ...device, brightness: parseInt(brightness) }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      this.addOperationRecord('brightness', `亮度调整为${brightness}%`)
      
    } catch (error) {
      console.error('调节亮度失败:', error)
    }
  },

  // 颜色变化
  async onColorChange(e) {
    const color = e.currentTarget.dataset.color
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        color: color
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { color: color })
      
      // 更新本地数据
      const updatedDevice = { ...device, color: color }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      const colorText = { warm: '暖色', natural: '自然', cool: '冷色' }[color]
      this.addOperationRecord('color', `色温调整为${colorText}`)
      
    } catch (error) {
      console.error('调节色温失败:', error)
    }
  },

  // 模式变化
  async onModeChange(e) {
    const mode = e.currentTarget.dataset.mode
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        mode: mode
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { mode: mode })
      
      // 更新本地数据
      const updatedDevice = { ...device, mode: mode }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      const modeText = { reading: '阅读', relax: '休闲', night: '夜灯' }[mode]
      this.addOperationRecord('mode', `切换到${modeText}模式`)
      
    } catch (error) {
      console.error('切换模式失败:', error)
    }
  },

  // 调整温度
  async adjustTemperature(e) {
    const delta = parseInt(e.currentTarget.dataset.delta)
    const device = this.data.currentDevice
    const currentTemp = device.temperature || 24
    const newTemp = Math.max(16, Math.min(30, currentTemp + delta))
    
    try {
      await deviceAPI.controlDevice(device.id, {
        temperature: newTemp
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { temperature: newTemp })
      
      // 更新本地数据
      const updatedDevice = { ...device, temperature: newTemp }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      this.addOperationRecord('temperature', `温度设置为${newTemp}°C`)
      
    } catch (error) {
      console.error('调节温度失败:', error)
    }
  },

  // 空调模式变化
  async onACModeChange(e) {
    const mode = e.currentTarget.dataset.mode
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        mode: mode
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { mode: mode })
      
      // 更新本地数据
      const updatedDevice = { ...device, mode: mode }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      const modeText = { cool: '制冷', heat: '制热', fan: '送风', dry: '除湿' }[mode]
      this.addOperationRecord('mode', `切换到${modeText}模式`)
      
    } catch (error) {
      console.error('切换空调模式失败:', error)
    }
  },

  // 风速变化
  async onWindSpeedChange(e) {
    const speed = e.currentTarget.dataset.speed
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        windSpeed: speed
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { windSpeed: speed })
      
      // 更新本地数据
      const updatedDevice = { ...device, windSpeed: speed }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      const speedText = { low: '低风', medium: '中风', high: '高风', auto: '自动' }[speed]
      this.addOperationRecord('wind', `风速调整为${speedText}`)
      
    } catch (error) {
      console.error('调节风速失败:', error)
    }
  },

  // 频道切换
  async changeChannel(e) {
    const delta = parseInt(e.currentTarget.dataset.delta)
    const device = this.data.currentDevice
    const currentChannel = device.channel || 1
    const newChannel = Math.max(1, Math.min(100, currentChannel + delta))
    
    try {
      await deviceAPI.controlDevice(device.id, {
        channel: newChannel
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { channel: newChannel })
      
      // 更新本地数据
      const updatedDevice = { ...device, channel: newChannel }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      this.addOperationRecord('channel', `切换到频道CCTV-${newChannel}`)
      
    } catch (error) {
      console.error('切换频道失败:', error)
    }
  },

  // 音量调节
  async onVolumeChange(e) {
    const volume = e.detail.value
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        volume: parseInt(volume)
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { volume: parseInt(volume) })
      
      // 更新本地数据
      const updatedDevice = { ...device, volume: parseInt(volume) }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      this.addOperationRecord('volume', `音量调整为${volume}%`)
      
    } catch (error) {
      console.error('调节音量失败:', error)
    }
  },

  // 信号源切换
  async onSourceChange(e) {
    const source = e.currentTarget.dataset.source
    const device = this.data.currentDevice
    
    try {
      await deviceAPI.controlDevice(device.id, {
        source: source
      })
      
      // 更新设备状态
      const app = getApp()
      await app.updateDeviceStatus(device.id, { source: source })
      
      // 更新本地数据
      const updatedDevice = { ...device, source: source }
      this.setData({ currentDevice: updatedDevice })
      
      // 添加操作记录
      const sourceText = { hdmi1: 'HDMI 1', hdmi2: 'HDMI 2', tv: '电视' }[source]
      this.addOperationRecord('source', `信号源切换到${sourceText}`)
      
    } catch (error) {
      console.error('切换信号源失败:', error)
    }
  },

  // 重新连接
  async onRetryConnect() {
    this.setData({ loading: true })
    
    try {
      // 模拟重新连接过程
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      // 刷新设备状态
      await this.loadDeviceDetail(this.data.deviceId)
      
      wx.showToast({
        title: '连接成功',
        icon: 'success'
      })
    } catch (error) {
      wx.showToast({
        title: '连接失败',
        icon: 'error'
      })
    }
  },

  // 添加操作记录
  addOperationRecord(type, description) {
    const now = new Date()
    const time = now.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
    const date = now.toLocaleDateString('zh-CN', { 
      month: 'short', 
      day: 'numeric' 
    })
    
    const record = {
      time: `今天 ${time}`,
      description: description,
      icon: this.getOperationIcon(type),
      type: type
    }
    
    const operationHistory = [record, ...this.data.operationHistory.slice(0, 9)]
    this.setData({ operationHistory })
  },

  // 获取操作图标
  getOperationIcon(type) {
    const iconMap = {
      'power_on': '/images/icons/power-on.png',
      'power_off': '/images/icons/power-off.png',
      'brightness': '/images/icons/brightness.png',
      'color': '/images/icons/color.png',
      'mode': '/images/icons/mode.png',
      'temperature': '/images/icons/temperature.png',
      'wind': '/images/icons/wind.png',
      'channel': '/images/icons/channel.png',
      'volume': '/images/icons/volume.png',
      'source': '/images/icons/source.png'
    }
    return iconMap[type] || '/images/icons/operation.png'
  },

  // 切换收藏
  onToggleFavorite() {
    const device = this.data.currentDevice
    const newFavoriteState = !device.isFavorite
    
    // 更新全局数据
    const app = getApp()
    const deviceIndex = app.globalData.deviceList.findIndex(d => d.id === device.id)
    if (deviceIndex !== -1) {
      app.globalData.deviceList[deviceIndex].isFavorite = newFavoriteState
    }
    
    // 更新本地数据
    const updatedDevice = { ...device, isFavorite: newFavoriteState }
    this.setData({ currentDevice: updatedDevice })
    
    wx.showToast({
      title: newFavoriteState ? '已收藏' : '已取消收藏',
      icon: 'success'
    })
  },

  // 分享设备
  onShareDevice() {
    wx.showActionSheet({
      itemList: ['分享给家人', '生成分享码', '复制设备信息'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            this.shareToFamily()
            break
          case 1:
            this.generateShareCode()
            break
          case 2:
            this.copyDeviceInfo()
            break
        }
      }
    })
  },

  // 设备设置
  onDeviceSettings() {
    wx.navigateTo({
      url: `/pages/device-settings/device-settings?deviceId=${this.data.deviceId}`
    })
  },

  // 设备重命名
  onRenameDevice() {
    wx.showModal({
      title: '重命名设备',
      content: '请输入新的设备名称',
      editable: true,
      placeholderText: this.data.currentDevice.name,
      success: (res) => {
        if (res.confirm && res.content) {
          this.renameDevice(res.content)
        }
      }
    })
  },

  // 执行重命名
  async renameDevice(newName) {
    try {
      // 更新全局数据
      const app = getApp()
      const deviceIndex = app.globalData.deviceList.findIndex(d => d.id === this.data.deviceId)
      if (deviceIndex !== -1) {
        app.globalData.deviceList[deviceIndex].name = newName
      }
      
      // 更新本地数据
      const updatedDevice = { ...this.data.currentDevice, name: newName }
      this.setData({ currentDevice: updatedDevice })
      
      wx.showToast({
        title: '重命名成功',
        icon: 'success'
      })
    } catch (error) {
      wx.showToast({
        title: '重命名失败',
        icon: 'error'
      })
    }
  },

  // 设备迁移
  onMoveDevice() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 固件升级
  onFirmwareUpdate() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 删除设备
  onDeleteDevice() {
    wx.showModal({
      title: '删除设备',
      content: '确定要删除这个设备吗？此操作不可撤销。',
      confirmColor: '#e74c3c',
      success: (res) => {
        if (res.confirm) {
          this.deleteDevice()
        }
      }
    })
  },

  // 执行删除设备
  async deleteDevice() {
    try {
      // 从全局数据中移除
      const app = getApp()
      app.globalData.deviceList = app.globalData.deviceList.filter(
        d => d.id !== this.data.deviceId
      )
      
      wx.showToast({
        title: '设备已删除',
        icon: 'success'
      })
      
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    } catch (error) {
      wx.showToast({
        title: '删除失败',
        icon: 'error'
      })
    }
  },

  // 分享给家人
  shareToFamily() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 生成分享码
  generateShareCode() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 复制设备信息
  copyDeviceInfo() {
    const device = this.data.currentDevice
    const info = `设备名称：${device.name}
设备类型：${this.getDeviceTypeText(device.type)}
设备ID：${device.id}
所在房间：${device.roomName}`
    
    wx.setClipboardData({
      data: info,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        })
      }
    })
  }
})